package kz.kstu.ds.utils;

import javax.swing.*;
import java.awt.*;

/**
 * Date: 03.11.12
 * Time: 21:21
 *
 * @author Oleg Anastassov
 */
public class GUIUtils {

    private static final int HEIGHT_INDENT = 50;
    private static final int WIDTH_INDENT = 50;

    private static Rectangle maxWindowBounds;

    private GUIUtils() {
    }

    /**
     * Returns max window bounds.
     *
     * @return The dimension of monitor size.
     */
    public static Rectangle monitorBounds() {
        if (maxWindowBounds != null) {
            return maxWindowBounds;
        }
        maxWindowBounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
        return maxWindowBounds;
    }

    /**
     * Returns max window size.
     *
     * @return The dimension of monitor size.
     */
    public static Dimension monitorSize() {
        //monitorSize = Toolkit.getDefaultToolkit().getScreenSize();
        Rectangle mb = monitorBounds();
        return new Dimension(mb.width, mb.height);
    }

    /**
     * Returns monitor size.
     *
     * @return The dimension of monitor size.
     */
    public static Dimension preferredStartupScreenSize() {
        Dimension ms = monitorSize();
        Dimension preferableSize = new Dimension();
        preferableSize.setSize(ms.getWidth() - WIDTH_INDENT, ms.getHeight() - HEIGHT_INDENT);
        return preferableSize;
    }

    /**
     * Make window centered and shown.
     *
     * @param aWindow The window for shown.
     */
    public static void centerAndShow(Window aWindow) {
        centerAndShow(aWindow, null);
    }

    public static void maximizeAndShowFrame(JFrame frame) {
        frame.setExtendedState(Frame.MAXIMIZED_BOTH);
        centerAndShow(frame);
    }

    public static void centerAndShow(Window aWindow, Window parent) {
        // aWindow.pack();

        Rectangle screen = parent != null ? parent.getBounds() : monitorBounds();
        Dimension window = aWindow.getSize();
        // ensure that no parts of aWindow will be off-screen
        if (window.height > screen.height) {
            window.height = screen.height;
        }
        if (window.width > screen.width) {
            window.width = screen.width;
        }

        int xCoord = screen.x + (screen.width / 2 - window.width / 2);
        int yCoord = screen.y + (screen.height / 2 - window.height / 2);

        aWindow.setLocation(xCoord, yCoord);
        aWindow.setVisible(true);
    }

}
